const express = require('express');
const router = express.Router();

const path = require('path');
const expressValidator = require('express-validator');
const check = expressValidator.check;
const validationResult = expressValidator.validationResult;

const db = require('../db/db').db;

// cookie 的最长失效时间，1小时
const COOKIE_MAXAGE = 60 * 60 * 1000;

// 创建application/x-www-form-urlencoded
router.use(require('body-parser').urlencoded({
    extended: true
}))

// 创建application/json解析
router.use(require('body-parser').json())

/* login */
let loginTemp = path.join(path.dirname(__dirname), 'views', 'login', 'index')
router.get('/', (req, res, next) => {
    res.render(loginTemp);
})
router.route('/login')
    .get((req, res, next) => {
        res.render(loginTemp);
    })
    .post([
        check('username')
            .not()
            .isEmpty()
            .withMessage('请输入用户名'),
        check('pwd')
            .not()
            .isEmpty()
            .withMessage('请输入密码')
    ], (req, res, next) => {
        let user = {
            username: req.body.username,
            pwd: req.body.pwd
        }
        let errors = validationResult(req)
        if (!errors.isEmpty()) {
            return res.render(loginTemp, {
                title: '登录',
                user: user,
                err: Object.values(errors.mapped())[0].msg
            })
        }
        // 查找用户
        let sqlStr = `
            SELECT * 
            FROM user 
            WHERE username = '${user.username}'
        `
        let connection = db.connection()
        db.query(connection, sqlStr, (err, result) => {
            try {
                // 未注册用户
                if (result.length == 0) {
                    // 重定向到注册页面
                    return res.redirect('/register')
                } else {
                    // 已注册用户
                    // 判定是否登录，若已登录直接进入主页
                    // 若未登录则登录后进入主页
                    let validateCon = db.connection()
                    let validateSql = `
                        SELECT *
                        FROM user
                        WHERE username = '${user.username}' AND password = '${user.pwd}'
                    `
                    db.query(validateCon, validateSql, (vErr, vResult) => {
                        try {
                            // 未找到密码相同用户
                            if (vResult.length == 0) {
                                return res.render(loginTemp, {
                                    user: user,
                                    err: '密码错误'
                                })
                            } else {
                                req.session.isLogin = true
                                res.cookie('isLogin', true, {
                                    expires: new Date(Date.now() + COOKIE_MAXAGE),
                                    maxAge: COOKIE_MAXAGE,
                                    signed: true
                                })
                                return res.redirect('/home')

                                // req.session.regenerate(() => {
                                //     req.session.isLogin = true
                                //     res.cookie('isLogin', true, {
                                //         expires: new Date(Date.now() + COOKIE_MAXAGE),
                                //         maxAge: COOKIE_MAXAGE,
                                //         signed: true
                                //     })
                                //     return res.redirect('/home')
                                // })
                            }
                        } catch (err) { }
                    })
                    db.close(validateCon)
                }
            } catch (err) { }
        })
        db.close(connection)
    })

/* register */
let registerTemp = path.join(path.dirname(__dirname), 'views', 'register', 'index')
router.route('/register')
    .get((req, res, next) => {
        res.render(registerTemp);
    })
    .post([
        check('username')
            .not()
            .isEmpty()
            .withMessage('请输入用户名'),
        check('pwd')
            .not()
            .isEmpty()
            .withMessage('请输入密码')
    ], (req, res, next) => {
        let user = {
            username: req.body.username,
            pwd: req.body.pwd
        }
        let errors = validationResult(req)
        if (!errors.isEmpty()) {
            return res.render(registerTemp, {
                user: user,
                err: Object.values(errors.mapped())[0].msg
            })
        }
        // 查找用户
        let sqlStr = `
            SELECT * 
            FROM user 
            WHERE username = '${user.username}'
        `
        let connection = db.connection()
        db.query(connection, sqlStr, (err, result) => {
            try {
                // 无重名用户，注册用户
                if (result.length == 0) {
                    let insertCon = db.connection()
                    let insertSql = `
                        INSERT INTO user(username, password)
                        VALUES('${user.username}', '${user.pwd}')
                    `
                    db.query(insertCon, insertSql, user, (id) => {
                        try {
                            return res.render(registerTemp, {
                                user: user,
                                err: '已注册，请返回登录'
                            })
                        } catch (err) { }
                    })
                    db.close(insertCon)
                } else {
                    // 有重名用户，提示用户名已被占用
                    return res.render(registerTemp, {
                        user: user,
                        err: '用户名已被占用'
                    })
                }
            } catch (err) { }
        })
        db.close(connection)
    })

/* home */
let homeTemp = path.join(path.dirname(__dirname), 'views', 'home', 'index')
router.route('/home')
    .get((req, res, next) => {
        res.render(homeTemp, {
            links: [{
                name: '项目列表',
                path: '/project'
            }, {
                name: '任务类型',
                path: '/tasktype'
            }, {
                name: '报告',
                path: '/report'
            }, {
                name: '任务补填',
                path: '/task/add?source=fill'
            }]
        })
    })

/* logout */
router.route('/logout')
    .get((req, res, next) => {
        req.session.destroy((err) => {
            if (err) {
                return false
            }
            res.clearCookie('isLogin')
            return res.redirect('/login')
        })
    })

module.exports = router;
